<template>
  <div>
    <el-drawer
      custom-class="wxkj-drawer featured-first-edit-drawer"
      :title="drawerTitle"
      :visible.sync="drawerShow"
      size="500px"
    >
      <div class="drawer-content">
        <el-form
          ref="form"
          label-width="150px"
          :model="form"
          :rules="rules"
        >
          <el-form-item v-show="false" label="id：" prop="id">
            <el-input v-model="form.id" />
          </el-form-item>
          <el-form-item label="标题：" prop="title">
            <el-input v-model="form.title" placeholder="" />
          </el-form-item>
          <el-form-item label="H5跳转url：" prop="redirect">
            <el-input v-model="form.redirect" placeholder="" />
          </el-form-item>
          <el-form-item label="是否新页面打开：" prop="open">
            <el-radio-group v-model="form.open">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="图片：" prop="image">
            <!-- <div class="upload-img">
              <el-upload
                :show-file-list="false"
                :multiple="false"
                action="https://jsonplaceholder.typicode.com/posts/"
                list-type="picture-card"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="form.image" :src="image">
                <i v-else class="el-icon-plus" />
              </el-upload>
            </div> -->
            <upload-cropper
              ref="uploadCropper"
              class="wrap"
              :style="{height:(310/(bannerWidth/bannerHeight))+'px' ,lineHeight:(310/(bannerWidth/bannerHeight))+'px'}"
              :enlarge="2"
              :init-img="banner"
              :auto-crop-width="bannerWidth"
              :tip-content="'只支持JPG格式,建议使用大小不要超过1000k、'+bannerWidth+'*'+bannerHeight+'像素的图片'"
              :fixed-number="[bannerWidth,bannerHeight]"
              @upload="getUploadImgId"
            />
          </el-form-item>
          <el-form-item label="排序：" prop="sequence">
            <el-input
              v-model="form.sequence"
              max-length="9"
              placeholder="填写整数"
              @input="formInput('sequence')"
              @keyup.enter.native="handleFilter"
            />
          </el-form-item>
          <el-form-item label="是否显示：" prop="disabled">
            <el-radio-group v-model="form.disabled">
              <el-radio :label="false">是</el-radio>
              <el-radio :label="true">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item class="fr">
            <el-button @click.native="drawerShow = false">取消</el-button>
            <el-button type="primary" :loading="waiting" @click.native="submit('form')">确认</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { blockDataAdd } from '@/api/block'
import uploadCropper from '@/components/uploadCropper'
export default {
  components: {
    uploadCropper
  },
  data() {
    var validateUploadImg = (rule, value, callback) => {
      if (value === '') {
        this.$refs.uploadCropper.uploadError(true)
        callback(new Error('请上传图片'))
      }
      callback()
    }
    return {
      drawerShow: false,
      drawerTitle: '',
      imageUrl: '',
      form: {
        id: '',
        blockId: '',
        type: '',
        image: '',
        title: '',
        redirect: '',
        sourceId: '',
        disabled: false,
        open: false,
        sequence: ''
      },
      rules: {
        image: [{ required: true, message: '请上传图片' }, { validator: validateUploadImg }]
      },
      banner: '',
      bannerWidth: 0,
      bannerHeight: 0,
      waiting: false
    }
  },
  watch: {
    drawerShow(bl) {
      if (!bl) {
        console.log(!bl)
        this.$refs.form.resetFields()
        this.banner = ''
        this.$refs.uploadCropper.initUpload()
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 销毁
  destroyed() {},
  // 方法
  methods: {
    // 输入整数
    formInput(e) {
      this.form[e] = this.form[e].replace(/[^\d]/g, '')
    },
    // 弹窗打开
    show(title, blockCode, bannerWidth, bannerHeight, rowData) {
      this.drawerTitle = title
      this.drawerShow = true
      this.form.blockId = blockCode
      this.bannerWidth = bannerWidth
      this.bannerHeight = bannerHeight
      // 编辑传参
      try {
        if (rowData) {
          Object.keys(this.form).forEach(k => {
            this.form[k] = rowData[k]
          })
          this.banner = rowData.image_dictText
        }
      } catch (e) {
        // TODO handle the exception
      }
    },
    // 父组件置顶
    // topThis(rowData) {
    //   try {
    //     if (rowData) {
    //       Object.keys(rowData).forEach(k => {
    //         this.form[k] = rowData[k]
    //       })
    //     }
    //   } catch (e) {
    //     // TODO handle the exception
    //   }
    //   // 置顶
    //   this.form.sequence = 1
    //   blockDataAdd([this.form]).then(response => {
    //     this.$message({
    //       type: 'success',
    //       message: '已置顶！'
    //     })
    //     this.$refs.form.resetFields()
    //     this.$emit('refresh')
    //   })
    // },
    // 保存
    submit(form) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.waiting = true
          blockDataAdd([this.form]).then(response => {
            this.$message({
              type: 'success',
              message: this.form.id ? '保存成功!' : '添加成功！'
            })
            this.drawerShow = false
            this.waiting = false
            this.$emit('refresh')
          }).catch(() => {
              this.waiting = false
            })
        }
      })
    },
    // 图片id
    getUploadImgId(id) {
      this.form.image = id
      this.$refs.form.clearValidate('image')
    }
  }
}
</script>
<style lang="scss">
  .wrap{
    width: 100%;
    div{width: 100%;height: 100%;line-height:inherit;}
  }
</style>
